package cn.xianshu.pet.service.impl;

import cn.xianshu.basic.service.impl.BasicServiceImpl;
import cn.xianshu.pet.domain.Pet;
import cn.xianshu.pet.domain.PetDetail;
import cn.xianshu.pet.mapper.PetDetailMapper;
import cn.xianshu.pet.mapper.PetMapper;
import cn.xianshu.pet.service.IPetService;
import org.apache.ibatis.builder.BuilderException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class PetServiceImpl  extends BasicServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void insert(Pet pet){
        // 先存pet 返回自增主键
        petMapper.insert(pet);
        // 再存petDetail
        PetDetail detail = pet.getDetail();
        detail.setPet_id(pet.getId());
        petDetailMapper.insert(detail);
    }

    /**
     * 宠物状态上架修改
     * @param ids
     */
    @Override
    public void onsale(List<Long> ids) {

        System.out.println(ids);
        // 参数判断，id不能为空
        if (ids == null || ids.size() == 0){
            throw new BuilderException("操作失败!");
        }
        // 宠物状态为下架才能上架
        // 批量查询待上架的数据
        List<Pet> list = petMapper.selectloadById(ids, Pet.OFFSALE_ID);

        Date date = new Date();
        // 修改宠物状态为上架
        list.forEach( pet -> {
            pet.setState(Pet.ONSALE_ID);
            pet.setOnsaletime(date);
            petMapper.update(pet);
        });
    }



    /**
     *
     * 宠物状态下架修改
     * @param ids
     */
    @Override
    public void offsale(List<Long> ids) {

        System.out.println(ids);
        // 参数判断，id不能为空
        if (ids == null || ids.size() == 0){
            throw new BuilderException("操作失败!");
        }
        // 宠物状态为下架才能上架
        // 批量查询待上架的数据
        List<Pet> list = petMapper.selectloadById(ids, Pet.ONSALE_ID);

        Date date = new Date();
        // 修改宠物状态为上架
        list.forEach( pet -> {
            pet.setState(Pet.OFFSALE_ID);
            pet.setOffsaletime(date);
            petMapper.update(pet);
        });
    }

    /**
     * 获取上线宠物详情
     * @param id
     * @return
     */
    @Override
    public Pet selectOnLineById(Long id) {
        return petMapper.selectOnLineById(id, Pet.ONSALE_ID);
    }
}
